<template>
  <view>
    <view class="title">修改密码</view>
    <view class="title2">请输入您的密码信息</view>

    <!-- 账号 -->
    <view class="username">
      <view class="label">账号：</view>
      <view class="value">{{ account.username }}</view>
    </view>

    <!-- 旧密码 -->
    <view class="password input">
      <input
        type="password"
        placeholder="旧密码"
        v-model="account.oldPassword"
        @blur="validateOldPassword"
      />
      <uni-icons type="eye-slash-filled" size="24" color="rgba(147, 147, 147, 1)"></uni-icons>
    </view>

    <!-- 新密码 -->
    <view class="password input">
      <input
        type="password"
        placeholder="新密码"
        v-model="account.newPassword"
        @blur="validatePasswordStrength"
      />
      <uni-icons type="eye-slash-filled" size="24" color="rgba(147, 147, 147, 1)"></uni-icons>
    </view>

    <!-- 确认新密码 -->
    <view class="password input">
      <input
        type="password"
        placeholder="确认新密码"
        v-model="account.confirmPassword"
        @blur="validatePasswordMatch"
      />
      <uni-icons type="eye-slash-filled" size="24" color="rgba(147, 147, 147, 1)"></uni-icons>
    </view>

    <!-- 确认修改按钮 -->
    <button @click="updatePassword">确认修改</button>

    <!-- 取消按钮 -->
    <button class="cancel-btn" @click="navigateBack">取消</button>

    <ErrorMessage
      v-if="isErrorVisible"
      :message="message"
      :visible="isErrorVisible"
      :type="errorType"
      @update:visible="isErrorVisible = false"
    />
  </view>
</template>

<script>
import { api } from '../../utils/api/user.js';
import ErrorMessage from '@/components/errorMessage/errorMessage.vue';

export default {
  components: {
    ErrorMessage,
  },
  data() {
    return {
      account: {
        username: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      message: '',
      isErrorVisible: false,
      errorType: 'error',
      isLoading: false
    };
  },
  onShow() {
    this.loadUserInfo();
  },
  methods: {
    showError(message, type = 'error') {
      this.message = message;
      this.errorType = type;
      this.isErrorVisible = true;
    },
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo && userInfo.username) {
        this.account.username = userInfo.username;
      } else {
        uni.redirectTo({ url: '/pages/login/login' });
      }
    },
    validatePasswordStrength() {
      if (!this.account.newPassword) {
        this.showError('请输入新密码');
        return false;
      }
      
      // 密码强度验证：至少6位，包含字母和数字
      const strongRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/;
      if (!strongRegex.test(this.account.newPassword)) {
        this.showError('密码需至少6位，包含字母和数字');
        return false;
      }
      return true;
    },
    validatePasswordMatch() {
      if (!this.account.confirmPassword) {
        this.showError('请确认新密码');
        return false;
      }
      
      if (this.account.newPassword !== this.account.confirmPassword) {
        this.showError('新密码和确认密码不一致');
        return false;
      }
      return true;
    },
    
    async validateOldPassword() {
      if (!this.account.oldPassword) {
        this.showError('请输入旧密码');
        return false;
      }
      
      if (this.isLoading) return false;
      
      this.isLoading = true;
      uni.showLoading({ title: '验证中...', mask: true });

      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.userId || !userInfo.token) {
          this.showError('用户信息不存在，请重新登录');
          uni.redirectTo({ url: '/pages/login/login' });
          return false;
        }
        
        console.log('正在获取用户信息...', { userId: userInfo.userId });
        const userData = await api.getUserById(userInfo.userId, userInfo.token);
        console.log('获取到的用户数据:', userData);
        
        if (!userData) {
          this.showError('获取用户信息失败，请重试');
          return false;
        }
        
        // 检查密码字段是否存在
        if (typeof userData.password === 'undefined') {
          console.error('用户数据中没有密码字段:', userData);
          this.showError('系统错误，缺少密码信息');
          return false;
        }
        
        // 验证旧密码是否匹配
        if (this.account.oldPassword !== userData.password) {
          console.log('密码不匹配:', {
            input: this.account.oldPassword,
            stored: userData.password
          });
          this.showError('旧密码不正确');
          return false;
        }
        
        return true;
      } catch (err) {
        console.error('验证旧密码失败:', err);
        let errorMsg = err.message || '验证旧密码失败';
        
        // 处理特定错误
        if (err.message.includes('token')) {
          errorMsg = '登录已过期，请重新登录';
          uni.redirectTo({ url: '/pages/login/login' });
        } else if (err.message.includes('未知错误')) {
          errorMsg = '系统错误，请稍后再试';
        }
        
        this.showError(errorMsg);
        return false;
      } finally {
        this.isLoading = false;
        uni.hideLoading();
      }
    },
    
    async updatePassword() {
      if (this.isLoading) return;
      
      // 验证所有字段
      if (!this.account.oldPassword) {
        this.showError('请输入旧密码');
        return;
      }
      
      if (!this.account.newPassword) {
        this.showError('请输入新密码');
        return;
      }
      
      if (!this.account.confirmPassword) {
        this.showError('请确认新密码');
        return;
      }
      
      if (!this.validatePasswordStrength()) return;
      if (!this.validatePasswordMatch()) return;
      
      this.isLoading = true;
      uni.showLoading({
        title: '正在修改...',
        mask: true
      });
      
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.userId || !userInfo.token) {
          this.showError('用户信息不完整，请重新登录');
          return;
        }
        
        // 先验证旧密码
        if (!await this.validateOldPassword()) return;
        
        const res = await api.user_update_api(
          userInfo.userId,
          userInfo.username,
          userInfo.email,
          this.account.newPassword,
          userInfo.token
        );
        
        console.log('修改密码响应:', res);
        
        // 修改为适应code=0表示成功的API
        if (res && res.code === 0) {
          uni.showToast({ 
            title: '密码修改成功', 
            icon: 'success',
            duration: 2000
          });
          
          // 更新本地存储的用户信息
          const updatedUserInfo = { 
            ...userInfo, 
            password: this.account.newPassword 
          };
          uni.setStorageSync('userInfo', updatedUserInfo);
          
          // 清空表单
          this.account.oldPassword = '';
          this.account.newPassword = '';
          this.account.confirmPassword = '';
          
          // 2秒后返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 2000);
        } else {
          const errorMsg = res?.msg || '密码修改失败';
          this.showError(errorMsg);
        }
      } catch (error) {
        let errorMsg = '修改失败，请检查网络后重试';
        if (error.response) {
          errorMsg = error.response.data?.message || errorMsg;
        } else if (error.message) {
          errorMsg = error.message;
        }
        this.showError(errorMsg);
        console.error('修改密码错误:', error);
      } finally {
        this.isLoading = false;
        uni.hideLoading();
      }
    },
    
    navigateBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style>
  /* 保持原有样式不变 */
  page {
    background-color: #FFF;
  }
  .title {
    margin: 110rpx 0 20rpx 50rpx;
    font-size: 64rpx;
    font-weight: 400;
    letter-spacing: 0rpx;
    line-height: 76rpx;
    color: rgba(51, 62, 99, 1);
    text-align: left;
    vertical-align: top;
  }
  .title2 {
    margin: 0rpx 0 120rpx 50rpx;
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.64rpx;
    line-height: 54rpx;
    color: rgba(147, 147, 147, 1);
    text-align: left;
    vertical-align: top;
  }
  .username {
    display: flex;
    font-size: 40rpx;
    margin: 40rpx 0 60rpx 80rpx;
  }
  .input {
    display: flex;
    margin: 0rpx 0 44rpx 40rpx;
    padding: 36rpx 0 6rpx 62rpx;
    width: 80%;
    height: 80rpx;
    background: rgba(247, 248, 249, 1);
    border-radius: 20rpx;
  }
  .input input {
    width: 80%;
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.4rpx;
    line-height: 56rpx;
    color: rgba(189, 189, 189, 1);
    text-align: left;
    vertical-align: middle;
  }
  button {
    margin-bottom: 30rpx;
    width: 300rpx;
    height: 100rpx;
    background: rgba(36, 204, 184, 1);
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0.4rpx;
    line-height: 100rpx;
    color: rgba(255, 255, 255, 1);
    text-align: center;
    vertical-align: middle;
    border-radius: 40rpx;
  }
  .cancel-btn {
    background: #f0f0f0 !important;
    color: #333 !important;
  }
</style>